﻿using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using System.Windows.Forms;
using System.Threading;


namespace PayRoller.Code
{
    public delegate string CreatePDFHandler(string inputUrl, string outPutDirString);

    public class PDFHelper
    {
        private static System.Drawing.Bitmap bitmap;
        private static string url;
        private static int w = 800, h = 900;

        public static void setBitmap()
        {
            using (WebBrowser wb = new WebBrowser())
            {
                wb.Width = w;
                wb.Height = h;
                wb.ScrollBarsEnabled = false;
                wb.Navigate(url);
                //wb.Navigate("http://localhost:81/manage/Reports/StatementDetails.aspx?Guid=29ba397f-6938-493e-93e6-9b74b1525cb6&OrgSid=15");
                //确保页面被解析完全
                while (wb.ReadyState != WebBrowserReadyState.Complete)
                {
                    System.Windows.Forms.Application.DoEvents();
                }
                bitmap = new System.Drawing.Bitmap(w, h);
                wb.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, w, h));
                wb.Dispose();
            }
        }


        public static string CreatPdf(string inputUrl, string outPutDirString)
        {
            string pdfFile = string.Empty;
            string fileName = string.Empty;
            
            Document doc = new Document(PageSize.A4, 9, 18, 36, 36);//左右上下
            MemoryStream ms = new MemoryStream();

            inputUrl = inputUrl.ToLower();
            string queryInfo = inputUrl.ToLower();
            if (queryInfo.Contains("guid="))
            {
                int guidPos = queryInfo.IndexOf("guid=");
                fileName = queryInfo.Substring(guidPos + 5);
                int otherPos = fileName.IndexOf("&");
                if (otherPos >= 0)
                {
                    fileName = fileName.Substring(0, otherPos);
                }
            }

            if (outPutDirString.EndsWith(Path.DirectorySeparatorChar.ToString()) == false)
            {
                outPutDirString += Path.DirectorySeparatorChar;
            }
            string outputFileWithoutExtention =outPutDirString+  fileName;

            try
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, ms);
                writer.CloseStream = false;
                doc.Open();
                url = inputUrl;
                Thread thread = new Thread(new ThreadStart(setBitmap));
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                while (thread.IsAlive)
                {
                    Thread.Sleep(100);
                }

                string outputImageFile = outputFileWithoutExtention + ".bmp";
                bitmap.Save(outputImageFile);

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
                img.ScalePercent(75);//560 630
                doc.Add(img);
            }
            catch
            {
                //throw new Exception(err.Message);
            }
            finally
            {
                doc.Close();
                pdfFile = outputFileWithoutExtention + ".pdf";
                using (FileStream fs = new FileStream(pdfFile, FileMode.Create))
                {
                    ms.Position = 0;
                    byte[] bit = new byte[ms.Length];
                    ms.Read(bit, 0, (int)ms.Length);
                    fs.Write(bit, 0, bit.Length);
                }
                ms.Close();
                ms.Dispose();
            }

            return pdfFile;
        }
    }
}